<template>
  <div class="follow-up-analytics">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>跟进数据统计</span>
          <el-radio-group v-model="dateRange" @change="handleDateRangeChange" size="small">
            <el-radio-button label="week">本周</el-radio-button>
            <el-radio-button label="month">本月</el-radio-button>
            <el-radio-button label="quarter">本季度</el-radio-button>
            <el-radio-button label="custom">自定义</el-radio-button>
          </el-radio-group>
        </div>
      </template>

      <!-- 自定义日期范围 -->
      <el-row v-if="dateRange === 'custom'" :gutter="20" class="date-range-row">
        <el-col :span="8">
          <el-date-picker
            v-model="customDateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="handleCustomDateChange"
            style="width: 100%"
          />
        </el-col>
      </el-row>

      <!-- 统计卡片 -->
      <el-row :gutter="20" class="stats-row">
        <el-col :xs="24" :sm="12" :md="6">
          <div class="stat-card">
            <div class="stat-icon follow-up">
              <el-icon><Phone /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-title">总跟进次数</div>
              <div class="stat-value">{{ analyticsData.totalFollowUps }}</div>
              <div class="stat-trend" :class="getTrendClass(analyticsData.followUpTrend)">
                <el-icon><CaretTop /></el-icon>
                {{ Math.abs(analyticsData.followUpTrend) }}%
              </div>
            </div>
          </div>
        </el-col>
        <el-col :xs="24" :sm="12" :md="6">
          <div class="stat-card">
            <div class="stat-icon customer">
              <el-icon><User /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-title">跟进客户数</div>
              <div class="stat-value">{{ analyticsData.totalCustomers }}</div>
              <div class="stat-trend" :class="getTrendClass(analyticsData.customerTrend)">
                <el-icon><CaretTop /></el-icon>
                {{ Math.abs(analyticsData.customerTrend) }}%
              </div>
            </div>
          </div>
        </el-col>
        <el-col :xs="24" :sm="12" :md="6">
          <div class="stat-card">
            <div class="stat-icon conversion">
              <el-icon><TrendCharts /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-title">转化率</div>
              <div class="stat-value">{{ analyticsData.conversionRate }}%</div>
              <div class="stat-trend" :class="getTrendClass(analyticsData.conversionTrend)">
                <el-icon><CaretTop /></el-icon>
                {{ Math.abs(analyticsData.conversionTrend) }}%
              </div>
            </div>
          </div>
        </el-col>
        <el-col :xs="24" :sm="12" :md="6">
          <div class="stat-card">
            <div class="stat-icon overdue">
              <el-icon><Warning /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-title">逾期跟进</div>
              <div class="stat-value">{{ analyticsData.overdueFollowUps }}</div>
              <div class="stat-trend negative">
                <el-icon><CaretBottom /></el-icon>
                {{ analyticsData.overdueTrend }}%
              </div>
            </div>
          </div>
        </el-col>
      </el-row>

      <!-- 图表区域 -->
      <el-row :gutter="20" class="charts-row">
        <el-col :xs="24" :lg="12">
          <el-card class="chart-card">
            <template #header>
              <span>跟进方式分布</span>
            </template>
            <div class="chart-container">
              <div ref="followUpMethodChart" style="height: 300px"></div>
            </div>
          </el-card>
        </el-col>
        <el-col :xs="24" :lg="12">
          <el-card class="chart-card">
            <template #header>
              <span>客户意向等级分布</span>
            </template>
            <div class="chart-container">
              <div ref="intentionLevelChart" style="height: 300px"></div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <el-row :gutter="20" class="charts-row">
        <el-col :xs="24" :lg="12">
          <el-card class="chart-card">
            <template #header>
              <span>跟进趋势图</span>
            </template>
            <div class="chart-container">
              <div ref="followUpTrendChart" style="height: 300px"></div>
            </div>
          </el-card>
        </el-col>
        <el-col :xs="24" :lg="12">
          <el-card class="chart-card">
            <template #header>
              <span>用户跟进统计</span>
            </template>
            <div class="chart-container">
              <div ref="userFollowUpChart" style="height: 300px"></div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 数据表格 -->
      <el-card class="table-card">
        <template #header>
          <span>详细统计数据</span>
        </template>
        <el-table :data="tableData" border style="width: 100%">
          <el-table-column prop="userName" label="用户姓名" min-width="120" />
          <el-table-column prop="totalFollowUps" label="总跟进次数" width="120" align="center" />
          <el-table-column prop="phoneCount" label="电话跟进" width="100" align="center" />
          <el-table-column prop="wechatCount" label="微信跟进" width="100" align="center" />
          <el-table-column prop="emailCount" label="邮件跟进" width="100" align="center" />
          <el-table-column prop="visitCount" label="上门跟进" width="100" align="center" />
          <el-table-column prop="avgIntentionLevel" label="平均意向等级" width="120" align="center" />
          <el-table-column prop="conversionCount" label="转化客户数" width="120" align="center" />
          <el-table-column prop="conversionRate" label="转化率" width="100" align="center">
            <template #default="{ row }">
              {{ row.conversionRate }}%
            </template>
          </el-table-column>
          <el-table-column prop="overdueCount" label="逾期次数" width="100" align="center" />
        </el-table>
      </el-card>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import * as echarts from 'echarts'
import { ElMessage } from 'element-plus'
import { getFollowUpAnalytics } from '@/api/crm'
import { Phone, User, TrendCharts, Warning, CaretTop, CaretBottom } from '@element-plus/icons-vue'

// 日期范围选择
const dateRange = ref('week')
const customDateRange = ref([])

// 分析数据
const analyticsData = reactive({
  totalFollowUps: 0,
  totalCustomers: 0,
  conversionRate: 0,
  overdueFollowUps: 0,
  followUpTrend: 0,
  customerTrend: 0,
  conversionTrend: 0,
  overdueTrend: 0,
  followUpMethodData: [],
  intentionLevelData: [],
  trendData: [],
  userData: []
})

// 表格数据
const tableData = ref([])

// 图表实例
const followUpMethodChart = ref<HTMLElement>()
const intentionLevelChart = ref<HTMLElement>()
const followUpTrendChart = ref<HTMLElement>()
const userFollowUpChart = ref<HTMLElement>()

let followUpMethodChartInstance: echarts.ECharts | null = null
let intentionLevelChartInstance: echarts.ECharts | null = null
let followUpTrendChartInstance: echarts.ECharts | null = null
let userFollowUpChartInstance: echarts.ECharts | null = null

// 获取趋势类名
const getTrendClass = (trend: number) => {
  return trend >= 0 ? 'positive' : 'negative'
}

// 获取日期范围参数
const getDateRangeParams = () => {
  const endDate = new Date()
  let startDate = new Date()
  
  switch (dateRange.value) {
    case 'week':
      startDate.setDate(endDate.getDate() - 7)
      break
    case 'month':
      startDate.setMonth(endDate.getMonth() - 1)
      break
    case 'quarter':
      startDate.setMonth(endDate.getMonth() - 3)
      break
    case 'custom':
      if (customDateRange.value && customDateRange.value.length === 2) {
        return {
          startDate: customDateRange.value[0],
          endDate: customDateRange.value[1]
        }
      }
      break
  }
  
  return {
    startDate: startDate.toISOString().split('T')[0],
    endDate: endDate.toISOString().split('T')[0]
  }
}

// 获取分析数据
const fetchAnalyticsData = async () => {
  try {
    const params = getDateRangeParams()
    const res = await getFollowUpAnalytics(params)
    
    Object.assign(analyticsData, res)
    tableData.value = res.userData || []
    
    // 更新图表
    updateCharts()
  } catch (error: any) {
    const errorMessage = error?.response?.data?.message || error?.message || '获取分析数据失败'
    ElMessage.error(errorMessage)
    console.error('获取分析数据失败:', error)
  }
}

// 初始化跟进方式分布图
const initFollowUpMethodChart = () => {
  if (!followUpMethodChart.value) return
  
  followUpMethodChartInstance = echarts.init(followUpMethodChart.value)
  
  const option = {
    tooltip: {
      trigger: 'item'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [
      {
        name: '跟进方式',
        type: 'pie',
        radius: '50%',
        data: analyticsData.followUpMethodData || [],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }
  
  followUpMethodChartInstance.setOption(option)
}

// 初始化客户意向等级分布图
const initIntentionLevelChart = () => {
  if (!intentionLevelChart.value) return
  
  intentionLevelChartInstance = echarts.init(intentionLevelChart.value)
  
  const option = {
    tooltip: {
      trigger: 'item'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [
      {
        name: '意向等级',
        type: 'pie',
        radius: '50%',
        data: analyticsData.intentionLevelData || [],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }
  
  intentionLevelChartInstance.setOption(option)
}

// 初始化跟进趋势图
const initFollowUpTrendChart = () => {
  if (!followUpTrendChart.value) return
  
  followUpTrendChartInstance = echarts.init(followUpTrendChart.value)
  
  const dates = analyticsData.trendData?.map(item => item.date) || []
  const counts = analyticsData.trendData?.map(item => item.count) || []
  
  const option = {
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      data: dates
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '跟进次数',
        type: 'line',
        data: counts,
        smooth: true,
        itemStyle: {
          color: '#409EFF'
        },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(64, 158, 255, 0.3)' },
            { offset: 1, color: 'rgba(64, 158, 255, 0.1)' }
          ])
        }
      }
    ]
  }
  
  followUpTrendChartInstance.setOption(option)
}

// 初始化用户跟进统计图
const initUserFollowUpChart = () => {
  if (!userFollowUpChart.value) return
  
  userFollowUpChartInstance = echarts.init(userFollowUpChart.value)
  
  const users = analyticsData.userData?.map(item => item.userName) || []
  const counts = analyticsData.userData?.map(item => item.totalFollowUps) || []
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    xAxis: {
      type: 'category',
      data: users,
      axisLabel: {
        interval: 0,
        rotate: 45
      }
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '跟进次数',
        type: 'bar',
        data: counts,
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#83bff6' },
            { offset: 0.5, color: '#188df0' },
            { offset: 1, color: '#188df0' }
          ])
        }
      }
    ]
  }
  
  userFollowUpChartInstance.setOption(option)
}

// 更新图表
const updateCharts = () => {
  // 更新跟进方式分布图
  if (followUpMethodChartInstance) {
    const option = {
      series: [
        {
          data: analyticsData.followUpMethodData || []
        }
      ]
    }
    followUpMethodChartInstance.setOption(option)
  }
  
  // 更新客户意向等级分布图
  if (intentionLevelChartInstance) {
    const option = {
      series: [
        {
          data: analyticsData.intentionLevelData || []
        }
      ]
    }
    intentionLevelChartInstance.setOption(option)
  }
  
  // 更新跟进趋势图
  if (followUpTrendChartInstance) {
    const dates = analyticsData.trendData?.map(item => item.date) || []
    const counts = analyticsData.trendData?.map(item => item.count) || []
    const option = {
      xAxis: {
        data: dates
      },
      series: [
        {
          data: counts
        }
      ]
    }
    followUpTrendChartInstance.setOption(option)
  }
  
  // 更新用户跟进统计图
  if (userFollowUpChartInstance) {
    const users = analyticsData.userData?.map(item => item.userName) || []
    const counts = analyticsData.userData?.map(item => item.totalFollowUps) || []
    const option = {
      xAxis: {
        data: users
      },
      series: [
        {
          data: counts
        }
      ]
    }
    userFollowUpChartInstance.setOption(option)
  }
}

// 日期范围变化
const handleDateRangeChange = () => {
  fetchAnalyticsData()
}

// 自定义日期变化
const handleCustomDateChange = () => {
  if (dateRange.value === 'custom') {
    fetchAnalyticsData()
  }
}

// 窗口大小变化处理
const handleResize = () => {
  followUpMethodChartInstance?.resize()
  intentionLevelChartInstance?.resize()
  followUpTrendChartInstance?.resize()
  userFollowUpChartInstance?.resize()
}

// 初始化
onMounted(() => {
  fetchAnalyticsData()
  
  // 初始化图表
  setTimeout(() => {
    initFollowUpMethodChart()
    initIntentionLevelChart()
    initFollowUpTrendChart()
    initUserFollowUpChart()
  }, 100)
  
  // 监听窗口大小变化
  window.addEventListener('resize', handleResize)
})

// 清理
onUnmounted(() => {
  followUpMethodChartInstance?.dispose()
  intentionLevelChartInstance?.dispose()
  followUpTrendChartInstance?.dispose()
  userFollowUpChartInstance?.dispose()
  
  window.removeEventListener('resize', handleResize)
})
</script>

<style scoped lang="scss">
.follow-up-analytics {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-wrap: wrap;
    gap: 10px;
  }

  .date-range-row {
    margin-bottom: 20px;
  }

  .stats-row {
    margin-bottom: 20px;
  }

  .stat-card {
    background: #fff;
    border-radius: 8px;
    padding: 20px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    display: flex;
    align-items: center;
    transition: transform 0.3s;

    &:hover {
      transform: translateY(-2px);
    }

    .stat-icon {
      width: 60px;
      height: 60px;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 15px;
      font-size: 24px;
      color: #fff;

      &.follow-up {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      }

      &.customer {
        background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
      }

      &.conversion {
        background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
      }

      &.overdue {
        background: linear-gradient(135deg, #fa709a 0%, #fee140 100%);
      }
    }

    .stat-content {
      flex: 1;

      .stat-title {
        font-size: 14px;
        color: #909399;
        margin-bottom: 8px;
      }

      .stat-value {
        font-size: 24px;
        font-weight: bold;
        color: #303133;
        margin-bottom: 8px;
      }

      .stat-trend {
        font-size: 12px;
        display: flex;
        align-items: center;

        &.positive {
          color: #67c23a;
        }

        &.negative {
          color: #f56c6c;
        }
      }
    }
  }

  .charts-row {
    margin-bottom: 20px;
  }

  .chart-card {
    height: 100%;
  }

  .chart-container {
    padding: 10px;
  }

  .table-card {
    margin-top: 20px;
  }

  // 响应式设计
  @media screen and (max-width: 768px) {
    .card-header {
      flex-direction: column;
      align-items: flex-start;
    }

    .stats-row {
      .stat-card {
        flex-direction: column;
        text-align: center;

        .stat-icon {
          margin-right: 0;
          margin-bottom: 15px;
        }
      }
    }
  }

  @media screen and (max-width: 480px) {
    .stat-card {
      padding: 15px;

      .stat-icon {
        width: 50px;
        height: 50px;
        font-size: 20px;
      }

      .stat-content {
        .stat-value {
          font-size: 20px;
        }
      }
    }
  }
}
</style>